package bb.lanxing.manager;

import static android.content.Context.LOCATION_SERVICE;

import android.Manifest;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.provider.Settings;

import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;

import java.util.HashSet;
import java.util.Set;

import bb.lanxing.App;

public class SystemLocationManagerNew {
    private static final String TAG = "SystemLocationManagerNew";
    private static final int TIME_INTERVAL = 1000;
    private static volatile SystemLocationManagerNew instance;
    private LocationManager mLocationManager;

    private Set<GpsChangedListener> mGpsChangedListenerSet;

    public static SystemLocationManagerNew getInstance() {
        if (instance == null) {
            synchronized (SystemLocationManagerNew.class) {
                if (instance == null) {
                    instance = new SystemLocationManagerNew();
                }
            }
        }
        return instance;
    }

    private SystemLocationManagerNew() {
        mLocationManager = (LocationManager) App.getContext().getSystemService(LOCATION_SERVICE);
        if (!mLocationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
            Settings.Secure.setLocationProviderEnabled(App.getContext().getContentResolver(), LocationManager.GPS_PROVIDER, true);
        }
        if (ActivityCompat.checkSelfPermission(App.getContext(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            return;
        }
        mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, TIME_INTERVAL, 0, mLocationListener);
    }

    private LocationListener mLocationListener = new LocationListener() {
        @Override
        public void onLocationChanged(@NonNull Location location) {
            if (mGpsChangedListenerSet != null) {
                for (GpsChangedListener gpsChangedListener : mGpsChangedListenerSet) {
                    synchronized (mGpsChangedListenerSet) {
                        gpsChangedListener.onLocationChanged(location);
                    }
                }
            }
        }
    };

    public void registerGpsChangedListener(GpsChangedListener listener) {
        if (mGpsChangedListenerSet == null) {
            mGpsChangedListenerSet = new HashSet();
        }
        mGpsChangedListenerSet.add(listener);
    }

    public void unregisterGpsChangedListener(GpsChangedListener listener) {
        if (mGpsChangedListenerSet != null) {
            mGpsChangedListenerSet.remove(listener);
        }
    }

    public static void terminate() {
        if (instance != null) {
//            instance.release();
            instance = null;
        }
    }

    public interface GpsChangedListener {
        public void onLocationChanged(@NonNull Location location);
    }
}